import store from '../store'
import config from '../config.js'

// 异步请求数据
const request = function(url, method, data, options = {}) {
	// 支持两种调用方式:
	// 1. request(url, method, data, options)
	// 2. request(options对象)
	let requestUrl, requestMethod, requestData, requestOptions, failCallback, completeCallback;
	
	// 判断调用方式并标准化参数
	if (typeof url === 'string') {
		// 参数形式调用: request(url, method, data, options)
		requestUrl = url;
		requestMethod = method || 'get';
		requestData = data || {};
		requestOptions = options || {};
	} else {
		// 对象形式调用: request(options)
		const optionsObj = url;
		requestUrl = optionsObj.url;
		requestMethod = optionsObj.method || 'get';
		requestData = optionsObj.data || {};
		requestOptions = optionsObj.options || {};
		failCallback = optionsObj.failCallback;
		completeCallback = optionsObj.completeCallback;
	}
	
	// 获取查询参数
	const params = requestOptions.params || {};
	
	// 确保URL有效
	if (!requestUrl) {
		console.error('Request URL is undefined');
		return Promise.reject(new Error('Request URL is undefined'));
	}
	
	// 确保URL以斜杠开头
	if (!requestUrl.startsWith('/')) {
		requestUrl = '/' + requestUrl;
	}
	
	// 添加查询参数到URL
	if (requestMethod.toLowerCase() === 'get' && Object.keys(params).length > 0) {
		const queryString = Object.keys(params)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
			.join('&');
		requestUrl += (requestUrl.includes('?') ? '&' : '?') + queryString;
	}
	
	// 记录请求日志
	console.log(`[请求][${requestMethod}] 完整URL:`, config.baseUrl + requestUrl);
	
	uni.showLoading({
		mask: true
	});
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.baseUrl + requestUrl,
			data: requestData,
			method: requestMethod,
			timeout: 5000,
			header: {
				'Content-Type': 'application/json; charset=UTF-8',
				'token': store.getters.getToken
			},
			success: res => {
				uni.hideLoading();
				console.log(`[请求][${requestMethod}][${requestUrl}] [返回结果]`, res.data);
				if (res.statusCode >= 200 && res.statusCode <= 300 ) {
					if (res.data.code === 200) {
						resolve(res.data);
					} else if (res.data.code === 10001) { 
						uni.showModal({
							title: '请先登录',
							content: '尚未登录或登录已过期',
							showCancel: false,
							confirmText: '去登录',
							success: function(e){
								if (e.confirm) {
									store.commit("logout");
									uni.reLaunch({
										url: "/pages/login/login"
									})
								}
							}
						});
						reject(new Error('尚未登录或登录已过期'));
					} else {
						const errorMsg = res.data.message || '请求失败';
						if (failCallback) {
							failCallback(errorMsg);
						} else {
							uni.showToast({
								title: errorMsg,
								duration: 1000,
								icon: 'none',
								mask: false
							});
						}
						reject(new Error(errorMsg));
					}
				} else { // http状态码 != 200
					const errorMsg = `请求异常: HTTP ${res.statusCode}`;
					uni.showToast({
						title: errorMsg,
						duration: 1000,
						icon: 'none',
						mask: false
					});
					reject(new Error(errorMsg));
				}
			},
			fail: (error) => {
				uni.hideLoading();
				const errorMsg = "服务器网络错误，请检查API地址配置是否正确";
				uni.showToast({
					title: errorMsg,
					duration: 1000,
					icon: 'none',
					mask: false
				});
				console.error(`[请求][${requestMethod}][${requestUrl}] [错误]`, error);
				console.error('请检查API地址配置:', config.baseUrl);
				
				// 开发环境显示更详细的错误信息
				if (config.debug) {
					uni.showModal({
						title: '网络请求失败',
						content: `请求URL: ${config.baseUrl}${requestUrl}\n\n错误信息: ${JSON.stringify(error)}`,
						showCancel: false
					});
				}
				
				reject(new Error(errorMsg));
			}, 
			complete() {
				if (completeCallback) {
					completeCallback();
				}
			}
		})
	})
}

export default request 